﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace JXT.PrimaryKey.Batman.Domain.Repositories.MySql.Expressions
{
    public class WhereQuery : ISqlQuery {
        protected StringBuilder sb = new StringBuilder();
        protected List<IDataParameter> parameterList = new List<IDataParameter>();

        public string QueryText
        {
            get
            {
                if (sb.Length <= 0)
                {
                    return "1 = 1";
                }
                return sb.ToString();
            }
        }

        public IDataParameter[] Parameters {
            get { return parameterList.ToArray(); }
        }

        internal WhereQuery() {
        }

        internal void Init(string text, params IDataParameter[] parameters) {
            if (sb.Length > 0)
                sb.Remove(0, sb.Length);
            parameterList.Clear();
            sb.Append(text);
            parameterList.AddRange(parameters);
        }

        internal void And(string text, params IDataParameter[] parameters) {
            if (sb.Length > 0)
                sb.AppendFormat(" {0} ", DbEnviroumentFactory.Instanse.AndTag);
            sb.Append(text);
            parameterList.AddRange(parameters);
        }

        internal void Or(string text, params IDataParameter[] parameters) {
            if (sb.Length > 0)
                sb.AppendFormat(" {0} ", DbEnviroumentFactory.Instanse.OrTag);
            sb.Append(text);
            parameterList.AddRange(parameters);
        }

        internal void And(WhereQuery query) {
            if (sb.Length > 0)
                sb.AppendFormat(" {0} ", DbEnviroumentFactory.Instanse.AndTag);
            sb.Append(query.QueryText);
            parameterList.AddRange(query.Parameters);
        }

        internal void Or(WhereQuery query) {
            if (sb.Length > 0)
                sb.AppendFormat(" {0} ", DbEnviroumentFactory.Instanse.OrTag);
            sb.Append(query.QueryText);
            parameterList.AddRange(query.Parameters);
        }
    }
}
